using System;
using System.Text;

namespace Sedge.Core.Configuration.Property
{
	public static class PropertyResolver
	{
		private enum ResolvingMode { Normal, Wait, Search }
	
		public static string ResolveValue(ReportableObject owner, string value)
		{
			if (owner == null || String.IsNullOrEmpty(value))
				return value;

			int startIndex = value.IndexOf("${");
			if (startIndex < 0)
				return value;

			ResolvingMode mode = ResolvingMode.Normal;

			StringBuilder output = new StringBuilder(value.Length);
			StringBuilder variable = new StringBuilder(value.Length);
			for (int i = 0; i < value.Length; i++)
			{
				char c = value[i];
				switch (mode)
				{
					case ResolvingMode.Normal:
					{
						if (c.Equals('$'))
							mode = ResolvingMode.Wait;
						else
							output.Append(c);
						break;
					}
					case ResolvingMode.Wait:
					{
						if (c.Equals('{'))
						{
							mode = ResolvingMode.Search;
							variable = new StringBuilder(value.Length);
						}
						else
						{
							mode = ResolvingMode.Normal;
							output.Append('$');
							output.Append(c);
						}
						break;
					}
					case ResolvingMode.Search:
					{
						if (c.Equals('}'))
						{
							mode = ResolvingMode.Normal;

							string key = variable.ToString();
							string propertyValue = owner.GetPropertyValue(key);
							if (!String.IsNullOrEmpty(propertyValue))
								output.Append(propertyValue);
						}
						else
						{
							variable.Append(c);
						}
						break;
					}
				}
			}
			return output.ToString();
		}

	}
}